/**
 * @description 片段-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const oxkit = require('@daelui/oxkit')
const parser = oxkit.parser
const Service = require('./service.js')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  queryView (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let params = action.params || {}
      return this.$service.query({
        params: {
          id: params.id || -9999
        },
        excute: {
          operators: [
            { field: 'id', operator: 'EQUAL' }
          ]
        }
      }).then(async (res) => {
        let data = res.data || {}
        let html = data.html || ''
        let css = data.css || ''
        let js = data.js || ''
        let vue = data.vue || ''
        // 查询路径数据
        let codes = []
        try {
          // 查询所有的分组数据
          let res = await this.$router.getControllInstance({path: '/tigerlair/dictionary'}).queryAll({}, {
            action: {},
            query: {},
            params: {
              cat: 'snippet-code',
              status: '1'
            }
          })
          let list = res.data
          list = Array.isArray(list) ? list : []
          codes = list
        } catch (e) {
          codes = []
        }
        codes.forEach(item => {
          html = this.replaceDict(html, item, action.req)
          css = this.replaceDict(css, item, action.req)
          js = this.replaceDict(js, item, action.req)
          vue = this.replaceDict(vue, item, action.req)
          html = this.replaceRequest(html, action.req)
          css = this.replaceRequest(css, action.req)
          js = this.replaceRequest(js, action.req)
          html = this.replaceRequest(html, action.req)
        })
        const resData = {
          success: 1,
          data: data
        }
        if (data.type === 'singlepage') {
          resData.data = html
          resData.type = 'PLAINHTML'
        } else {
          data.html = html
          data.vue = vue
          data.css = css
          data.js = js
        }

        return resData
      })
    })
  }

  queryRelease (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let params = action.params || {}
      return this.$router.getControllInstance({path: '/tigerlair/snippetrelease'}).query({}, {
        action: {},
        query: {},
        params: {
          id: params.rid,
          sid: params.id || -9999,
          status: '1'
        },
        excute: {
          operators: [
            { field: 'id', operator: 'EQUAL' },
            { field: 'sid', operator: 'EQUAL' }
          ]
        }
      }).then(async (res) => {
        let data = res.data || {}
        let html = data.html || ''
        let css = data.css || ''
        let js = data.js || ''
        let vue = data.vue || ''
        // 查询路径数据
        let codes = []
        try {
          // 查询所有的分组数据
          let res = await this.$router.getControllInstance({path: '/tigerlair/dictionary'}).queryAll({}, {
            action: {},
            query: {},
            params: {
              cat: 'snippet-code',
              status: '1'
            }
          })
          let list = res.data
          list = Array.isArray(list) ? list : []
          codes = list
        } catch (e) {
          codes = []
        }
        codes.forEach(item => {
          html = this.replaceDict(html, item, action.req)
          css = this.replaceDict(css, item, action.req)
          js = this.replaceDict(js, item, action.req)
          vue = this.replaceDict(vue, item, action.req)
          html = this.replaceRequest(html, action.req)
          css = this.replaceRequest(css, action.req)
          js = this.replaceRequest(js, action.req)
          html = this.replaceRequest(html, action.req)
        })
        const resData = {
          success: 1,
          data: data
        }
        if (data.type === 'singlepage') {
          resData.data = html
          resData.type = 'PLAINHTML'
        } else {
          data.html = html
          data.vue = vue
          data.css = css
          data.js = js
        }

        return resData
      })
    })
  }

  replaceDict (str, dict, request) {
    if (typeof str !== 'string') {
      return str
    }
    if (/{|\[/.test(dict.value) && /protocol|host|referer|method|port|default/i.test(dict.value)) {
      let headers = request.headers
      try {
        let list = []
        try {
          list = parser.parse(dict.value)
        } catch(e) {
          console.log(e)
          list = []
        }
        list = Array.isArray(list) ? list : [list]
        let def = list.find(item => item.default)
        let value = null
        list.forEach(item => {
          if (item.protocol && new RegExp(item.protocol, 'i').test(request.protocol)) {
            value = item.value
          } else if (item.host && new RegExp(item.host, 'i').test(request.hostname)) {
            value = item.value
          } else if (item.method && new RegExp(item.method, 'i').test(request.method)) {
            value = item.value
          } else if (item.port) {
            let reg = new RegExp(item.port, 'i')
            if (reg.test(request.hostname) || reg.test(headers.host)) {
              value = item.value
            }
          } else if (item.referer && new RegExp(item.referer, 'i').test(headers.referer)) {
            value = item.value
          }
        })
        if (value === null) {
          value = (def || {}).value
        }
        if (value !== null && value !== undefined) {
          str = str.replaceAll(dict.code, value)
        }
      } catch (e) {}
    } else {
      str = str.replaceAll(dict.code, dict.value)
    }
    return str
  }

  replaceRequest (str, request) {
    if (typeof str !== 'string') {
      return str
    }
    // request
    str = str.replace('{%request.method%}', request.method)
    str = str.replace('{%request.headers.host%}', request.headers.host)
    str = str.replace('{%request.headers.referer%}', request.headers.referer)
    
    return str
  }
}

module.exports = Controller